package com.qianguo.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.eva.androidlibrary.widget.SwipeRefreshRecyclerView;
import com.qianguo.shop.R;
import com.eva.androidlibrary.api.HttpRequestCallback;
import com.qianguo.shop.base.BaseTitleActivity;
import com.qianguo.shop.constant.ShopKeys;
import com.eva.androidlibrary.api.entity.Product;
import com.eva.androidlibrary.api.entity.ProductList;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品管理页面
 *
 * @author GUXIA318
 * @date 2015-11-25 17:55
 */
@EActivity(R.layout.activity_product_manager)
public class ProductManagerActivity extends BaseTitleActivity implements View.OnClickListener {

    /**
     * 所有
     */
    @ViewById(R.id.product_filter_all_text_view)
    TextView mTvFilterAll;

    /**
     * 添加时间
     */
    @ViewById(R.id.product_filter_time_text_view)
    TextView mTvFilterTime;

    /**
     * 种类
     */
    @ViewById(R.id.product_filter_kinds_text_view)
    TextView mTvFilterKind;

    /**
     * 销量
     */
    @ViewById(R.id.product_filter_sale_volume_text_view)
    TextView mTvFilterSale;

    @ViewById(R.id.product_recycler_view)
    SwipeRefreshRecyclerView mRecyclerView;

    @ViewById(R.id.product_list_view)
    ExpandableListView mExpandableListView;

    @Extra(ShopKeys.EXTRA_KEY_SHOP_ID)
    String mShopID;

    private int mCurrentPage = 1;
    private static final int PER_PAGE = 10;

    private View mCurFilterView;

    private ProductListAdapter mAdapter;
    private List<Product> mProducts = new ArrayList<>();

    private PopupMenu mPopupMenu;

    public static void jumpToProductManager(Context context, String shopID) {
        Intent intent = new Intent();
        intent.setClass(context, com.qianguo.shop.activity.ProductManagerActivity_.class);
        intent.putExtra(ShopKeys.EXTRA_KEY_SHOP_ID, shopID);
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return getString(R.string.product_manager_title);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_add) {
            if (mPopupMenu == null) {
                mPopupMenu = new PopupMenu(this, mToolbar, Gravity.RIGHT);
                mPopupMenu.getMenuInflater().inflate(R.menu.menu_add_product, mPopupMenu.getMenu());
                mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        AddOrEditProductActivity.jumpToEditProduct(ProductManagerActivity.this, mShopID, null);
                        return true;
                    }
                });
            }
            mPopupMenu.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add, menu);
        return true;
    }

    @Override
    protected void initializeUI() {
        mCurFilterView = mTvFilterAll;
        mTvFilterAll.setSelected(true);
        mTvFilterAll.setOnClickListener(this);
        mTvFilterTime.setOnClickListener(this);
        mTvFilterKind.setOnClickListener(this);
        mTvFilterSale.setOnClickListener(this);

//        mAdapter = new ProductListAdapter(this);
//        mExpandableListView.setAdapter(mAdapter);
//        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
//            @Override
//            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//                AddOrEditProductActivity.jumpToEditProduct(ProductManagerActivity.this, mShopID, mAdapter.getChild(groupPosition, childPosition));
//                return true;
//            }
//        });

        mAdapter = new ProductListAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setSwipeRefreshListener(new SwipeRefreshRecyclerView.SwipeRefreshListener() {
            @Override
            public void onLoadMore() {
                loadData(++mCurrentPage, PER_PAGE);
            }

            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                loadData(mCurrentPage, PER_PAGE);
            }
        });
        mRecyclerView.setOnItemClickListener(new SwipeRefreshRecyclerView.OnRecyclerItemClickListener() {
            @Override
            public void onClick(int position) {
                AddOrEditProductActivity.jumpToEditProduct(ProductManagerActivity.this, mShopID, mProducts.get(position));
            }
        });

        if (!TextUtils.isEmpty(mShopID)) {
            loadData(mCurrentPage, PER_PAGE);
        }
    }

    @Override
    public void onClick(View v) {
        mCurFilterView.setSelected(false);
        mCurFilterView = v;
        v.setSelected(true);
    }

    @Background
    void loadData(int page, int perpage) {
        mApp.getApi().getProducts(mApp.getUser().getToken(), mShopID, page, perpage, new HttpRequestCallback<ProductList>() {
            @Override
            public void onSuccess(int code, String msg, ProductList data) {
                mProducts.addAll(data.getList());
                renderUI();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(ProductManagerActivity.this, msg);
            }
        });
    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void renderUI() {
        mRecyclerView.onCompleted();
        mAdapter.notifyDataSetChanged();
    }

    public class ProductListAdapter extends RecyclerView.Adapter<ProductViewHolder> {

        private Context mContext;
        public ProductListAdapter(Context context) {
            this.mContext = context;
        }

        @Override
        public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.item_product_child, null);
            v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ProductViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ProductViewHolder holder, int position) {
            holder.onBind(mProducts.get(position));
        }

        @Override
        public int getItemCount() {
            return mProducts == null ? 0 : mProducts.size();
        }
    }

    public class ProductViewHolder extends RecyclerView.ViewHolder {

        ImageView imgCover;
        TextView tvName;
        TextView tvRegion;
        TextView tvPrice;
        TextView tvSales;

        public ProductViewHolder(View itemView) {
            super(itemView);
            imgCover = (ImageView) itemView.findViewById(R.id.product_cover_image_view);
            tvName = (TextView) itemView.findViewById(R.id.product_name_text_view);
            tvRegion = (TextView) itemView.findViewById(R.id.product_produce_field_text_view);
            tvPrice = (TextView) itemView.findViewById(R.id.product_price_text_view);
        }

        public void onBind(Product product) {
            mImageLoader.loadImage(ProductManagerActivity.this, imgCover, product.getCover());
            tvName.setText(product.getName());
            tvRegion.setText(product.getRegion());
            tvPrice.setText(product.getPrice() + "/" + product.getUnit());
        }
    }
//    public class ProductListAdapter extends BaseExpandableListAdapter {
//
//        Context mContext;
//
//        public ProductListAdapter(Context context) {
//            mContext = context;
//        }
//
//        @Override
//        public int getGroupCount() {
//            return mCategoryProducts != null ? mCategoryProducts.length : 0;
//        }
//
//        @Override
//        public int getChildrenCount(int groupPosition) {
//            Product[] products = mCategoryProducts[groupPosition].getProducts();
//            return products != null ? products.length : 0;
//        }
//
//        @Override
//        public CategoryProduct getGroup(int groupPosition) {
//            return mCategoryProducts[groupPosition];
//        }
//
//        @Override
//        public Product getChild(int groupPosition, int childPosition) {
//            return mCategoryProducts[groupPosition].getProducts()[childPosition];
//        }
//
//        @Override
//        public long getGroupId(int groupPosition) {
//            return groupPosition;
//        }
//
//        @Override
//        public long getChildId(int groupPosition, int childPosition) {
//            return childPosition;
//        }
//
//        @Override
//        public boolean hasStableIds() {
//            return false;
//        }
//
//        @Override
//        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//            GroupViewHolder holder;
//            if (convertView == null) {
//                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_product_group, null);
//                holder = new GroupViewHolder(convertView);
//                convertView.setTag(holder);
//            } else {
//                holder = (GroupViewHolder) convertView.getTag();
//            }
//
//            CategoryProduct item = getGroup(groupPosition);
//            holder.tvCategoryName.setText(item.getCategoryName());
//            holder.tvCategoryCount.setText(Integer.toString(item.getCount()));
//            return convertView;
//        }
//
//        @Override
//        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//            ChildViewHolder holder;
//            if (convertView == null) {
//                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_product_child, null);
//                holder = new ChildViewHolder(convertView);
//                convertView.setTag(holder);
//            } else {
//                holder = (ChildViewHolder) convertView.getTag();
//            }
//
//            Product item = getChild(groupPosition, childPosition);
//            mImageLoader.loadImage(mContext, holder.imgCover, item.getCover());
//            holder.tvName.setText(item.getName());
//            holder.tvProduceField.setText(getString(R.string.key_value_template, getString(R.string.product_key_produce_field), item.getRegion()));
//            holder.tvPrice.setText(getString(R.string.key_value_template, getString(R.string.product_key_price), String.valueOf(item.getPrice())));
//            return convertView;
//        }
//
//        @Override
//        public boolean isChildSelectable(int groupPosition, int childPosition) {
//            return true;
//        }
//    }
//
//    public class GroupViewHolder {
//        TextView tvCategoryName;
//        TextView tvCategoryCount;
//
//        public GroupViewHolder(View itemView) {
//            tvCategoryName = (TextView) itemView.findViewById(R.id.product_kind_name_text_view);
//            tvCategoryCount = (TextView) itemView.findViewById(R.id.product_kind_count_text_view);
//        }
//    }
//
//    public class ChildViewHolder {
//
//        ImageView imgCover;
//        TextView tvName;
//        TextView tvProduceField;
//        TextView tvPrice;
//        TextView tvSales;
//
//        public ChildViewHolder(View itemView) {
//            imgCover = (ImageView) itemView.findViewById(R.id.product_cover_image_view);
//            tvName = (TextView) itemView.findViewById(R.id.product_name_text_view);
//            tvProduceField = (TextView) itemView.findViewById(R.id.product_produce_field_text_view);
//            tvPrice = (TextView) itemView.findViewById(R.id.product_price_text_view);
////            tvSales = itemView.findViewById(R.id.product_)
//        }
//    }
}
